package com.Prot2;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.PowerManager.WakeLock;
import android.text.format.Time;
import android.util.Log;

import com.Prot2.Logger.AccelerationWorker;
import com.Prot2.Logger.BatteryWorker;
import com.Prot2.Logger.GPSWorker;
import com.Prot2.Logger.GyroWorker;
import com.Prot2.Logger.HumidityWorker;
import com.Prot2.Logger.LightWorker;
import com.Prot2.Logger.PressureWorker;
import com.Prot2.Logger.RecognitionWorker;
import com.Prot2.Logger.TemperatureWorker;
import com.Prot2.Logger.WiFiWorker;


public class Globals {

	private static final String TAG = "Globals";
	
	public static AccelerationWorker accelerationWorker;
	public static GyroWorker gyroWorker;
	public static LightWorker lightWorker;
	public static HumidityWorker humidityWorker;
	public static TemperatureWorker temperatureWorker;
	public static PressureWorker pressureWorker;
	public static RecognitionWorker recognitionWorker;
	public static GPSWorker gpsWorker;
	public static WiFiWorker wifiWorker;
	public static BatteryWorker batteryWorker;
	
	public static WifiManager mWifiManager;
	
	
	
	public static File logFile;
	public static File balanceFile;
	public static int samplingRate;
	public static int samplingTime;
	public static int waitTime;
	public static int contextToggleInterval;
	public static Time now;
	public static int currentLocationTag;
	public static int dataTableCounter;
	public static double[][] dataTable;
	
	public static int currentlyDetectedLabel;
	public static int previouslyDetectedLabel;
	public static int currentlyEstablishedLabel;
	
	public static int balanceContextMajorityTime;
	public static int balanceContextMajorityWindow;
	
	public static int[] togglingPreferences;
	public static double[] balanceGoal;

	
	public static final String appPath="Prot2";
	
	
	public static int contextSteady;
	public static int contextSteadyRequired;

	public static boolean gathererIsLogging;
	public static boolean balancingActive;
	public static int balancingUiUpdateRate;
	
	public static String dirPath;
	public static String logFilePath;
	public static String balanceFilePath;

	
	public static void init(){
		gathererIsLogging = false;
		
		samplingRate = 200;
		samplingTime = 5000;
		waitTime = 5000;
		contextToggleInterval = 5000;
		now = new Time();
		currentLocationTag = 0;
		currentlyDetectedLabel=20;
		previouslyDetectedLabel =20;
		currentlyEstablishedLabel = 20;
		
		contextSteady= 0;
		contextSteadyRequired = 2;
		
		balanceContextMajorityTime = 10*60*1000;
		balanceContextMajorityWindow = balanceContextMajorityTime/(samplingTime+waitTime);
		
		balancingActive=false;
		balancingUiUpdateRate= 5*1000;//balanceContextMajorityWindow*(samplingTime+waitTime);
		
//		togglingPreferences = new int[] {2,2,0,0,0,
//										 3,1,3,1,1,
//										 0,0,1,0,3};
		
		togglingPreferences = new int[] {0,0,0,0,0,
										 0,0,0,0,0,
										 0,0,0,0,0};
		
		balanceGoal = new double[] {0.44,0.32,0.07,0.12,0.05,0}; //Balance goals in format Home,Office,Indoor Other, Outdoor, Transport, Other
		

		
		
		dirPath=Environment.getExternalStorageDirectory()+"/"+appPath+"/DATA/"+getLogFolder()+"/";
		logFilePath=dirPath+"log_"+getDateAndTimeStamp()+".txt";
		
		balanceFilePath=Environment.getExternalStorageDirectory()+ "/" + appPath +"/DATA/balance.txt";
		
	}

	public static String getLogFolder(){
		int logId = 1;
		File f = new File(Environment.getExternalStorageDirectory()+ "/" + appPath +"/DATA/");
		File [] fileList = f.listFiles();
    	
    	if(fileList!=null){
    		logId=fileList.length+1;
    		}
    	Log.w(TAG,"created folder: "+Environment.getExternalStorageDirectory()+ "/" + appPath +"/DATA/"+logId); //keeps generating new locations, but cannot access files somehow... RESOLVED: Need to reboot device to access files
		return ""+logId;
	}
	
	public static String getDateAndTimeStamp(){
		now.setToNow();
		return ""+now.monthDay+"-"+(now.month+1)+"-"+now.year+"_"+now.hour+"-"+now.minute;
	}
	
	
	public static void createLogFile(){
		logFile = new File(logFilePath);
		
        try {
        	new File(dirPath).mkdirs();
        } catch (Exception e) {
            //nothing
        }
		
		if (logFile.exists()){
			//Intent intent = MainActivity.getIntent();
			//LoggerFileUI.finish();
			//startActivity(intent);
			logFile.delete();
			Log.w(TAG,"deleted existing logfile: "+logFilePath);
		}
		try{
			logFile.createNewFile();
			Log.w(TAG,"created logfile: "+logFilePath);}
		catch (IOException e){
			e.printStackTrace();
		}
	}
	
	public static void createBalanceFile(){
		balanceFile = new File(balanceFilePath);
		
		if (balanceFile.exists()){}else{
		try{
			balanceFile.createNewFile();
			Log.w(TAG,"created balancefile: "+balanceFilePath);}
		catch (IOException e){
			e.printStackTrace();
		}
		}}
	
	
	public static void makeFileEntry(String entry, File targetFile){
		
		FileOutputStream os;
		try {
			os = new FileOutputStream(targetFile, true);
			OutputStreamWriter out = new OutputStreamWriter(os, "UTF-8");
			out.write(entry);
			out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public static String logHeader(String DELIMITER){
		return "timestamp"+DELIMITER
				+"System Time"+DELIMITER
				+"X-Acceleration"+DELIMITER
				+"Y-Acceleration"+DELIMITER
				+"Z-Acceleration"+DELIMITER
			//	+"X-AngVelocity"+DELIMITER
			//	+"Y-AngVelocity"+DELIMITER
			//	+"Z-AngVelocity"+DELIMITER
				+"Light"+DELIMITER
				+"Humidity"+DELIMITER
				+"Temperature"+DELIMITER
				+"Pressure"+DELIMITER
				+"Location"+DELIMITER
				+"GPS status"+DELIMITER
				+"Latitude"+DELIMITER
				+"Longitude"+DELIMITER
				+"WIFI"+DELIMITER
				+"Battery"+DELIMITER
				+System.getProperty("line.separator");
	}
	
	
}
